#include <iostream>
#include <stdio.h>
#include <memory>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

#define ERR_EXIT(m) \
    do\
    {\
        perror(m);\
        exit(EXIT_FAILURE);\
    }while(0) 
#define MSGMAX 8192
struct msgbuf1
{
    /* data */
    long mtypc;
    char mtext[8192];
};

void echo_cli(int msgid)
{
    int pid;
    pid = getpid();
    struct msgbuf1 msg;
    memset(&msg, 0, sizeof(msg));
    *((int *)msg.mtext) = pid;
    msg.mtypc = 1;
    int n;

    while(fgets((msg.mtext+4), MSGMAX-5, stdin) != NULL)
    {

        msg.mtypc = 1;
        if(msgsnd(msgid, &msg, 4 + strlen(msg.mtext +4), 0) < 0)
            ERR_EXIT("msgsnd");
        memset(msg.mtext+4, 0, MSGMAX-4);
        sleep(10);
        if(n = msgrcv(msgid, &msg, MSGMAX,pid,0) < 0)
            ERR_EXIT("msgrcv");

        fputs(msg.mtext + 4, stdout);
        memset(msg.mtext+4, 0, MSGMAX-4);

    }
}

int main(int argv, char**argc)
{
    printf("************  message queue client!!!   **************\n");
    /* add test code! */
    int msgid;
    msgid = msgget(1234, 0);
    if(msgid == -1)
        ERR_EXIT("msgget");

    echo_cli(msgid);

    
    return 0;
}



